/**
 * Created by zhoulin on 2019/4/3.
 */

//表格初始化配置
var tableInit = function(){

    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        },{
            field: 'id',
            title: 'ID',
            align: 'center',
            sortable: true
        },{
            field: 'username',
            title: '用户名',
            align: 'center',
            sortable: true
        },{
            field: 'nickname',
            title: '昵称',
            align: 'center',
            sortable: true
        },{
            field: 'wx_tel',
            title: '微信绑定手机号码',
            align: 'center'
        },{
            field: 'tel',
            title: '常用手机号码',
            align: 'center'
        },{
            field: 'email',
            title: '邮箱',
            align: 'center'
        },{
            field: 'role_name',
            title: '角色',
            align: 'center'
        },{
            field: 'status',
            title: '状态',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return '<span class="label label-danger" >禁用</span>';
                } else if (value == 1) {
                    return '<span class="label label-primary" >正常</span>';
                } else {
                    return "其他";
                }

            }
        },{
            field: 'gmt_create',
            title: '创建时间',
            align: 'center',
            sortable: true,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            searchText: params.searchText
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST+_API.admin_sysBusiness_list, queryParams, columns),{
        //这里是其他的一些个性化的 bootstrap-table options
        //例如 覆盖一些公共的配置
        //例如 添加一些私有的配置
        showColumns: true,//列显示操作按钮
        ajaxOptions:{ //设置自定义请求头
            headers: {
                'Authorization':sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding':'business:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if(res.success){
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token,res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '输入用户名/昵称/手机号码/邮箱');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions:['business:add','business:update','business:del','business:resetPass','business:batchStatus','business:assignRoles'],//本页权限数组
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200)

            return ;
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //添加
        add:function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "edit.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
             layer.full(index);
        },
        //修改
        update:function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            list = list[0];
            var index = layer.open({
                type: 2,
                title: "修改",
                content: "edit.html?id="+list.id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
             layer.full(index);
        },
        //删除
        del:function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            for (var item in list) {
                ids += list[item].id + ",";
            }
            var confirm = layer.confirm('确定删除选中用户？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that,_HOST+_API.admin_sysBusiness_delete+ids,{},true,that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response)
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if(response){
                            if(response.success){
                                layer.msg(response.msg, {time: 1500, icon:1});
                            }else {
                                layer.msg(response.msg, {time: 1500, icon:5});
                            }
                        }
                    })
            });

        },
        //重置密码
        resetPass:function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var confirm = layer.confirm('确定重置选中用户登录密码？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that,_HOST+_API.admin_sysBusiness_resetPS,list[0],true,that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response)
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if(response){
                            if(response.success){
                                layer.msg(response.msg+"！【重置密码为：123456】", {icon: 1});
                            }else {
                                layer.msg(response.msg, {time: 1500, icon:5});
                            }
                        }
                    })
            });

        },
        //账号批处理
        batchStatus:function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            layer.open({
                title: '状态设置',
                icon: 3,
                content:'请选择状态!',
                shadeClose: false,
                btn: ['启用','禁用'],
                btn1: function(){
                    console.log("启用")
                    for (var item in list) {
                        list[item].status = 1;
                    }
                    Put(that,_HOST+_API.admin_sysBusiness_batchStatus,list,true,that.permissions[index])
                        .then(function (response) {
                            // 响应成功回调
                            console.log(response)
                            $('#bootstrapTableEvents').bootstrapTable('refresh');
                            if(response){
                                if(response.success){
                                    layer.msg(response.msg, {icon: 1});
                                }else {
                                    layer.msg(response.msg, {time: 1500, icon:5});
                                }
                            }
                        })
                },
                btn2: function(){
                    console.log("禁用")
                    for (var item in list) {
                        list[item].status = 0;
                    }
                    Put(that,_HOST+_API.admin_sysBusiness_batchStatus,list,true,that.permissions[index])
                        .then(function (response) {
                            // 响应成功回调
                            console.log(response)
                            $('#bootstrapTableEvents').bootstrapTable('refresh');
                            if(response){
                                if(response.success){
                                    layer.msg(response.msg, {icon: 1});
                                }else {
                                    layer.msg(response.msg, {time: 1500, icon:5});
                                }
                            }
                        })
                },

            });
        },
        //分配角色
        assignRoles:function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            //获取当前登录人拥有的角色
            Get(that,_HOST+_API.admin_sysBusinessRole_getAllRole+list[0].company_id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response)
                    if(response){
                        if(response.success){
                            console.log(response.list)
                            var html = "<div id='roses'>";
                            for (var item in response.list) {
                                html = html + '<label class="checkbox-inline i-checks"><input type="checkbox" name="roleId" value="'+response.list[item].id+'"> '+response.list[item].name+'</label>'
                            }
                            html+="</div>"

                            var confirm = layer.confirm(html, {
                                title:"角色",
                                btn: ['分配角色', '取消'], //按钮
                                shadeClose: false,
                                area:['50%','50%']
                            }, function () {
                                console.log("确定")
                                //选中角色
                                var aRoleList = [];
                                var roleId = [];
                                $("#roses input[name='roleId']:checked").each(function () {
                                    aRoleList.push({"bid": list[0].id, 'rid': $(this).val()})
                                    roleId.push({'rid': $(this).val()})
                                })

                                if (roleId.length <= 0) {
                                    layer.msg('请选择角色', {time: 1500, icon: 5});
                                    return;
                                }

                                Put(that,_HOST+_API.admin_sysBusinessRole_modifyUserRole,aRoleList,true,that.permissions[index])
                                    .then(function (response) {
                                        // 响应成功回调
                                        console.log(response)
                                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                                        if(response){
                                            if(response.success){
                                                layer.msg(response.msg, {icon: 1});
                                            }else {
                                                layer.msg(response.msg, {time: 1500, icon:5});
                                            }
                                        }
                                    })

                            });
                            $(".i-checks").iCheck({checkboxClass: "icheckbox_square-green",radioClass: "iradio_square-green",});

                            Get(that,_HOST+_API.admin_sysBusinessRole_getUserRole+list[0].id)
                                .then(function (response) {
                                    console.log(response.list)
                                    for (var item in response.list) {
                                        $("#roses input[name='roleId'][value='" + response.list[item].rid + "']").iCheck('check');
                                    }
                                })

                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })

        }
    },
})

$(function () {
    //初始化表格
    tableInit();
});